const express = require('express')

const app = express()
app.use(express.static('./public'))
// http
app.get('/',(req,res) => {
  res.send({ok:1})
})




// webscoket 
const WebSocket = require('ws');

const wss = new WebSocket.WebSocketServer({ port: 8080 });

wss.on('connection', function connection(ws) {
  ws.on('error', console.error);

  ws.on('message', function message(data, isBinary) {
    console.log('received: %s', data);

    // 转发给其他人,广播机制
    wss.clients.forEach(function each(client) {
      // client !== ws排除自己
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(data, { binary: isBinary });
      }
    });
  });

  ws.send('欢迎来到聊天室');
});


app.listen(3000)